//
//  messageViewController.m
//  随便点
//
//  Created by MWJ on 15/3/12.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "messageViewController.h"
#import "AppDelegate.h"
#import "message.h"
#import "messageTableViewCell.h"
#define zifu 20
@interface messageViewController (){
    NSDictionary *dic;
    NSMutableArray *array;
    AppDelegate *app;
    NSString *jiekoustr;
    NSString *str1;
    NSString *str2;
    NSString *str3;
    NSString *xinxishu;
}

@property (nonatomic,strong)RefreshControl * refreshControl;

@end

@implementation messageViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"zixingche"]]];
        self.navigationItem.title=@"消息中心";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    array = [NSMutableArray array];
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    //默认跳过条数为0
    str3 = @"0";
    
    [self loading];
    
    //上拉刷新
    
    _refreshControl=[[RefreshControl alloc] initWithScrollView:self.tableview delegate:self];
    _refreshControl.topEnabled=NO;
    _refreshControl.bottomEnabled=YES;
    
    [self.tableview reloadData];
    
    // Do any additional setup after loading the view.
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction==RefreshDirectionTop)
    {
        
        [array removeAllObjects];
        
    }
    else if (direction==RefreshDirectionBottom)
    {
        
    }
    
    __weak typeof(self)weakSelf=self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf=weakSelf;
        [strongSelf reloadData];
    });
    
}

-(void)reloadData
{
    
    str3=[NSString stringWithFormat:@"%d",[str3 intValue]+10];
    
    [self loading];
    
    if (self.refreshControl.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refreshControl.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionBottom];
        
    }
    
    [self.tableview reloadData];
}

-(void)loading{
    
    str1 = @"http://www.51anys.com:8080/waimaiwang/user/message/";
    str2 = app._id;

    jiekoustr = [NSString stringWithFormat:@"%@%@/%@",str1,str2,str3];
    
    NSURL *url=[NSURL URLWithString:jiekoustr];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        NSMutableArray *array1 = [NSMutableArray array];
        dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
        xinxishu = [NSString stringWithFormat:@"%@", dic[@"count"]];
        int instr = [xinxishu intValue];
        if (instr == 0) {
            [self label];
        }else{
        array1 = dic[@"list"];
        for (NSDictionary *obj in array1) {
            message *mess = [[message alloc]init];
            mess.nr = obj[@"content"];
            mess.shijian = obj[@"date"];
            [array addObject:mess];
        }
        }
        [self.tableview reloadData];
    }];
}
-(void)refreshData:(NSArray *)sender{
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return array.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"aaa";
    messageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    message *ms = array[indexPath.row];
    cell.NeiRong.text =[NSString stringWithFormat:@"%@", ms.nr];
//    cell.NeiRong.preferredMaxLayoutWidth = cell.NeiRong.bounds.size.width;
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[ms.shijian doubleValue]/1000];
    NSString *timeSp = [formatter stringFromDate:confromTimesp];
    cell.Time.text=timeSp;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)label{
    UILabel *lab = [[UILabel alloc]init];
    CGFloat labX = 100;
    CGFloat labY = 100;
    CGFloat labW = zifu * 6;
    CGFloat labH = zifu;
    lab.textColor = [UIColor redColor];
    lab.text = @"没有相关消息";
    lab.font = [UIFont systemFontOfSize:20];
    lab.frame = CGRectMake(labX, labY, labW, labH);
    [self.view addSubview:lab];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
